package api

//
import (
	"gitee.com/tietang/terrace-go/v2/base"
	"gitee.com/tietang/terrace-go/v2/base/starter/iiris"
	"gitee.com/tietang/terrace-go/v2/example/order"
	"github.com/kataras/iris/v12"
)

func init() {
	base.RegisterApi(&OrderApi{})
}

type OrderApi struct {
	iiris.BaseIrisApi
	service order.OrderService
}

func (a *OrderApi) Init() {
	a.service = order.GetOrderService()
	a.GroupRouter = iiris.Iris().Party("/v1/order")
	a.GroupRouter.Post("/create", a.createHandler)
	//通过path参数来创建
	a.GroupRouter.Post("/changeStatus", a.changeStatusHandler)
	a.GroupRouter.Get("/get/{tradeNo:string}", a.getHandler)
}

//定义账户创建接口/v1/order/create
func (api *OrderApi) createHandler(context iris.Context) {

	cdto := order.OrderCreatedDTO{}
	err := context.ReadJSON(&cdto)
	r := base.Res{
		Code: base.ResCodeOk,
	}
	if err != nil {
		r.Code = base.ResCodeRequestParamsError
		r.Message = err.Error()
		context.JSON(&r)
		return
	}

	dto, err := api.service.Create(cdto)

	if err != nil {
		r.Code = base.ResCodeInnerServerError
		r.Message = err.Error()
	}
	r.Data = dto
	context.JSON(r)
}

//查询订单信息的web接口：/v1/order/get
func (a *OrderApi) getHandler(ctx iris.Context) {
	accountNo := ctx.URLParam("tradeNo")
	r := base.Res{
		Code: base.ResCodeOk,
	}
	if accountNo == "" {
		r.Code = base.ResCodeRequestParamsError
		r.Message = "订单交易编号不能为空"
		ctx.JSON(&r)
		return
	}
	order := a.service.Get(accountNo)
	r.Data = order
	ctx.JSON(&r)
}

//修改订单状态的web接口：/v1/order/changeStatus
func (api *OrderApi) changeStatusHandler(context iris.Context) {

	cdto := order.OrderChangeStatusDTO{}
	err := context.ReadJSON(&cdto)
	r := base.Res{
		Code: base.ResCodeOk,
	}
	if err != nil {
		r.Code = base.ResCodeRequestParamsError
		r.Message = err.Error()
		context.JSON(&r)
		return
	}
	status, err := api.service.ChangeStatus(cdto)

	if err != nil {
		r.Code = base.ResCodeInnerServerError
		r.Message = err.Error()
	}

	r.Data = status
	context.JSON(r)
}
